/*
 * @Description:
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2024-02-08 12:56:45
 * @LastEditTime: 2024-02-08 15:50:51
 */
import { ref, watch } from "../utils/vue.esm.js";
const template = /*html*/ `
  <svg v-if="showBackToTop" class="back-to-top-icon" 
      :class="{show}"
      @click="goToTop"
      viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M320.32 368.192h384v64.128h-384zM383.808 304.064h257.024v64.128H383.808z" fill="#4C4C4C"></path><path d="M446.784 240h131.008v64.128H446.784zM479.552 175.872h65.472V240H479.552zM64.256 528h256v64.128h-256zM160.192 592.128h64.128v256H160.192zM384.256 528.128h64.128v320H384.256zM576.64 528h64.128v320H576.64z" fill="#4C4C4C"></path><path d="M384.256 528h256v64.128h-256zM384.256 784h256v64.128h-256zM704.256 528h64.128v320h-64.128z" fill="#4C4C4C"></path><path d="M704.256 528h192v64.128h-192zM704.256 656h192v64.128h-192zM896.256 528.128h64.128v192h-64.128z" fill="#4C4C4C"></path></svg>
`;
export default {
  template,
  setup() {
    // 动画
    const showBackToTop = ref(window.scrollY >= 300);
    const show = ref(true);

    watch(show, (val) => {
      if (!val) {
        setTimeout(() => {
          showBackToTop.value = false;
        }, 500);
      }
    });

    watch(showBackToTop, (val) => {
      if (val) {
        setTimeout(() => {
          show.value = true;
        });
      }
    });

    // 回到顶部动画
    const goToTop = () => {
      let top = window.scrollY;
      const speed = Math.ceil(top / 10);
      const scrollToTop = () => {
        top -= speed;
        top = top <= 0 ? 0 : top;
        window.scrollTo({ top });
        top > 0 && requestAnimationFrame(scrollToTop);
      };
      requestAnimationFrame(scrollToTop);
    };

    // 滚动跟随
    window.addEventListener("scroll", () =>{
      if (window.scrollY >= 300) {
        showBackToTop.value || (showBackToTop.value = true);
      } else {
        show.value && (show.value = false);
      }
    });

    return { showBackToTop, goToTop, show };
  },
};
